<?php
	function getCompanyByField($value, $field = "id")
	{
		global $connection;
		$queryParams = array();
		
		$queryParams[] = $_SESSION["language"]["id"];
		
		$query = "SELECT us.*, usd.description, usd.meta_description, usd.meta_keywords, c.name AS city_name, co.name AS county_name  
					FROM user_shops us
					LEFT JOIN user_shop_details usd ON us.id = usd.user_shop_id AND usd.language_id = ?
					LEFT JOIN counties co ON us.county_id = co.id 
					LEFT JOIN cities c ON us.city_id = c.id 
					 
			WHERE ";
		
		if($field == "id" || $field == "url")
		{
			$queryParams[] = $value;
			$query .= " us.$field = ?";
		}
		
		$company = $connection->fetch_one($query, $queryParams);
		
		if($company)
		{
			$company["num_rows"] = $connection->num_rows("SELECT * FROM products WHERE shop_id = ? AND visible = 1", array($company["id"]));
		}
		
		return $company;
	}
	
	function getCompanies($orderBy = "creation_date", $sortOrder = "asc", $limit = null)
	{
		global $connection;
		
		$languageID = $_SESSION["language"]["id"];
		
		$params[] = $languageID;
		
		$query = "SELECT usd.*, us.*, us.id AS id, c.name AS city_name, co.name AS county_name  
						FROM user_shops us
					LEFT JOIN user_shop_details usd ON usd.user_shop_id = us.id 
					LEFT JOIN cities c ON us.city_id = c.id 
					LEFT JOIN counties co ON us.county_id = co.id 
					WHERE usd.language_id = ?";
					
		if($sortOrder != "asc")
		{
			$sortOrder = "desc";
		}
		
		$query .= " GROUP BY us.id";
		
		if($orderBy == "creation_date" || $orderBy == "name" || $orderBy == "url" || $orderBy == "created")
		{
			$query .= " ORDER BY {$orderBy} $sortOrder";
		}
		
		if($limit != null)
		{
			$query .= " LIMIT $limit";
		}
		
		$companies = $connection->fetch_result($query, $params);
		
		return $companies;
	}
?>